from datetime import datetime
import markdown
from app import db

# 文章与标签的关联表
post_tag = db.Table('post_tag',
    db.Column('post_id', db.Integer, db.ForeignKey('posts.id'), primary_key=True),
    db.Column('tag_id', db.Integer, db.ForeignKey('tags.id'), primary_key=True)
)

class Post(db.Model):
    __tablename__ = 'posts'
    
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))
    slug = db.Column(db.String(255), unique=True, index=True)
    body = db.Column(db.Text)
    body_html = db.Column(db.Text)
    summary = db.Column(db.Text)
    created = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    published = db.Column(db.Boolean, default=True)
    featured_image = db.Column(db.String(255))
    views = db.Column(db.Integer, default=0)
    
    # 外键
    author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    
    # 关系
    comments = db.relationship('Comment', backref='post', lazy='dynamic', cascade='all, delete-orphan')
    tags = db.relationship('Tag', secondary=post_tag, backref=db.backref('posts', lazy='dynamic'))
    
    def __init__(self, **kwargs):
        super(Post, self).__init__(**kwargs)
        if self.body:
            self.on_body_changed()
    
    def on_body_changed(self):
        self.body_html = markdown.markdown(self.body, extensions=[
            'markdown.extensions.fenced_code',
            'markdown.extensions.codehilite',
            'markdown.extensions.tables',
            'markdown.extensions.toc',
            'mdx_math'
        ])
        # 生成摘要 (取前200个字符)
        plain_text = self.body[:200].replace('#', '').replace('*', '')
        self.summary = plain_text + '...' if len(self.body) > 200 else plain_text
    
    def increment_views(self):
        self.views += 1
        db.session.add(self)
    
    def __repr__(self):
        return f'<Post {self.title}>'